package com.daffodil.jasypt.util;

import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.PBEConfig;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;

/**
 * 配置文件数据安全加密工具
 * @author yweijian
 * @date 2021年2月7日
 * @version 1.0
 * @description
 */
public class JasyptUtils {
	
	/**
	 * 加密
	 * @param password 加密盐
	 * @param value 加密值
	 * @return
	 */
	public static String encyptPwd(String password, String value) {
		PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
		encryptor.setConfig((PBEConfig) cryptor(password));
		String result = encryptor.encrypt(value);
		return result;
	}

	/**
	 * 解密
	 * @param password 解密盐
	 * @param value 解密值
	 * @return
	 */
	public static String decyptPwd(String password, String value) {
		PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
		encryptor.setConfig((PBEConfig) cryptor(password));
		String result = encryptor.decrypt(value);
		return result;
	}

	/**
	 * jasyp加解密配置
	 * @param password
	 * @return
	 */
	private static SimpleStringPBEConfig cryptor(String password) {
		SimpleStringPBEConfig config = new SimpleStringPBEConfig();
		config.setPassword(password);
		config.setAlgorithm("PBEWithMD5AndDES");
		config.setKeyObtentionIterations("1000");
		config.setPoolSize("1");
		config.setProviderName("SunJCE");
		config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
		config.setIvGeneratorClassName("org.jasypt.iv.NoIvGenerator");
		config.setStringOutputType("base64");
		return config;
	}
}
